import { BASE_URL } from './util'
const app = getApp()
const server = BASE_URL

const setheader = () => {
  let token = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''
  return {
    'Content-Type': 'application/json',
    'XX-Token': token,
    'XX-Device-Type': 'wxapp'
  }
}

const get = ({ url, params }) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: server + url,
      method: 'get',
      data: params,
      header: setheader(),
      success: (res) => {
        if (res.data.code == '2000') {
          resolve(res.data)
        } else if (res.data.code == '403') {
          wx.showToast({
            title: res.data.msg || '请登录',
            icon: 'none',
            duration: 1000,
            success: function () {
              setTimeout(function () {
                app.removeLoginInfo()
              }, 1000)
            }
          })
          reject(res.data.msg)
        } else {
          wx.showToast({
            title: res.data.msg || '请求出错',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          reject(res.data)
        }
      },
      fail: (res) => {
        wx.showToast({
          title: res.data.msg || '',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        reject('网络出错')
      },
      complete: function () {
        // wx.hideLoading()
      }
    })
  })
}

const post = ({ url, params }) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: server + url,
      method: 'post',
      data: params,
      header: setheader(),
      success: (res) => {
        if (res.data.code == '2000') {
          resolve(res.data)
        } else if (res.data.code == '403') {
          wx.showToast({
            title: res.data.msg || '请登录',
            icon: 'none',
            duration: 1000,
            success: function () {
              setTimeout(function () {
                app.removeLoginInfo()
              }, 1000)
            }
          })
          reject(res.data.msg)
        } else {
          wx.showToast({
            title: res.data.msg || '请求出错',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          reject(res.data)
        }
      },
      fail: (res) => {
        wx.showToast({
          title: res.data.msg || '',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        reject('网络出错')
      },
      complete: function () {
        // wx.hideLoading()
      }
    })
  })
}



module.exports = {
  get: get,
  post: post,
}
